package com.herui.iot.ui.evaluation.execute;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.herui.device_lib.presenter.DevicePresenter;
import com.herui.device_lib.presenter.DevicePresenterInter;
import com.herui.device_lib.presenter.SimDevicePresenter;
import com.herui.sdyu_lib.utils.ToastUtil;
import com.herui.sport_care.R;
import com.herui.sport_care.data.SimDataFactory;
import com.herui.sport_care.data.check.DeviceInfo;
import com.herui.sport_care.data.check.EquipmentType;
import com.herui.sport_care.data.check.EvalUserInfo;
import com.herui.sport_care.data.check.EvaluationStage;
import com.herui.sport_care.data.eval.EvalInfo;
import com.herui.sport_care.ui.BaseSportFragment;
import com.herui.sport_care.ui.dialog.BpManagerDialog;
import com.herui.sport_care.ui.dialog.PopDialog;
import com.herui.sport_care.ui.dialog.SpoManagerDialog;
import com.proton.view.EcgRealTimeView;
import com.protontek.healthy.sdkcore.sphygmomanometer.api.BPDataBean;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class QuietCheckFragment extends BaseSportFragment {

    @BindView(R.id.view_user)
    View view_user;
    @BindView(R.id.view_ecg_device)
    View view_ecg_device;
    @BindView(R.id.tv_user)
    TextView tv_user;
    @BindView(R.id.tv_ecg)
    TextView tv_ecg;

    @BindView(R.id.id_ecg_view)
    EcgRealTimeView id_ecg_view;

    @BindView(R.id.view_ecg_content)
    View view_ecg_content;
    @BindView(R.id.tv_heart)
    TextView tv_heart;
    @BindView(R.id.tv_heart_statistics)
    TextView tv_heart_statistics;
    @BindView(R.id.tv_connect_ecg)
    TextView tv_connect_ecg;

    @BindView(R.id.view_bp_detect)
    View view_bp_detect;
    TextView tv_bp;
    TextView tv_connect_bp;
    @BindView(R.id.view_spo_detect)
    View view_spo_detect;
    TextView tv_spo;
    TextView tv_connect_spo;

    @BindView(R.id.btn_check)
    Button btn_check;

    private QuietCheckPresenter quietCheckPresenter;
    private DevicePresenterInter devicePresenter;
    private ExecteServerPresenter execteServerPresenter;

    // 被选择的用户
    private EvalUserInfo evalUserInfo;
    // 被选择的心电设备
    private DeviceInfo ecgDeviceInfo;
    // 评估id
    private Long evaluationSchemeId;
    private EvalInfo evalInfo;
    private FragmentLis fragmentLis;

    // 最大最小心率
    private boolean isConnectEcg;

    public static QuietCheckFragment newInstance(EvalInfo evalInfo, FragmentLis fragmentLis) {
        QuietCheckFragment fragment = new QuietCheckFragment(evalInfo, fragmentLis);
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public static interface FragmentLis{
        // 回调选择的心电设备
        void onResult(DeviceInfo ecgDeviceInfo);
    }

    public QuietCheckFragment(EvalInfo evalInfo, FragmentLis fragmentLis) {
        this.evalInfo = evalInfo;
        this.fragmentLis = fragmentLis;
        evaluationSchemeId = evalInfo.getEvaluationSchemeId();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        quietCheckPresenter = new QuietCheckPresenter(view, evalInfo);
        devicePresenter = quietCheckPresenter.getDevicePresenter();
        execteServerPresenter = new ExecteServerPresenter(ecServerView);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        tv_bp = view_bp_detect.findViewById(R.id.tv_bp);
        tv_connect_bp = view_bp_detect.findViewById(R.id.tv_connect_bp);
        tv_spo = view_spo_detect.findViewById(R.id.tv_spo);
        tv_connect_spo = view_spo_detect.findViewById(R.id.tv_connect_spo);
        tv_connect_bp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClick(v);
            }
        });
        tv_connect_spo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClick(v);
            }
        });

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        quietCheckPresenter.stop();
    }

    @Override
    public boolean onBackPressedSupport() {
        Long checkDuration = quietCheckPresenter.getCheckDuration();
        if (checkDuration != null && checkDuration < 5 * 60) {
            ToastUtil.showMessage("正在静息测量，无法退出");
            return false;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_quiet_check;
    }

    @Override
    public void initParam() {
        view_ecg_content.setVisibility(View.GONE);
        tv_connect_ecg.setVisibility(View.VISIBLE);
        tv_bp.setVisibility(View.GONE);
        tv_connect_bp.setVisibility(View.VISIBLE);
        tv_spo.setVisibility(View.GONE);
        tv_connect_spo.setVisibility(View.VISIBLE);

        btn_check.setText("开始静息测量");

//        simData();
        quietCheckPresenter.start();
    }

    private void simData(){
        evalUserInfo = SimDataFactory.getEvalUserInfo();
        tv_user.setText(evalUserInfo.getName());
        quietCheckPresenter.setEvalUserInfo(evalUserInfo);
    }

    @OnClick({R.id.view_user, R.id.view_ecg_device, R.id.tv_connect_ecg, R.id.btn_check})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.view_user:
                // 查询用户列表
                execteServerPresenter.findAwaitItemList(evaluationSchemeId, 0);
                break;
            case R.id.view_ecg_device:
                // 查询可用心电设备列表
                if (evalUserInfo == null) {
                    ToastUtil.showMessage("请先选择用户");
                    return;
                }
                execteServerPresenter.getAvailableEquipmentList(evaluationSchemeId,
                        evalUserInfo.getUserId(), EquipmentType.ECG_EQUIPMENT);
                break;
            case R.id.tv_connect_ecg:
                // 连接心电设备
                if (ecgDeviceInfo == null) {
                    ToastUtil.showMessage("请先选择心电设备");
                } else {
                    devicePresenter.connectEcg(ecgDeviceInfo.getMac());
                }
                break;
            case R.id.tv_connect_bp:
                // 连接血压
                new BpManagerDialog(baseActivity, devicePresenter, (bpDataBean) -> {

                });
                break;
            case R.id.tv_connect_spo:
                new SpoManagerDialog(baseActivity, devicePresenter, () -> {

                });
                break;
            case R.id.btn_check:
                Long checkDuration = quietCheckPresenter.getCheckDuration();
                if (checkDuration == null) {
                    if (ecgDeviceInfo == null) {
                        ToastUtil.showMessage("请先选择心电设备");
                        return;
                    }
                    if (!isConnectEcg) {
                        devicePresenter.connectEcg(ecgDeviceInfo.getMac());
                    }
                    quietCheckPresenter.startCheck();
                    btn_check.setText("结束静息检测(00:00)");
                } else {
                    if (checkDuration < 5*60) {
                        ToastUtil.showMessage("正在静息测量，无法退出");
                    } else {
                        quietCheckPresenter.finish();
                    }
                }
                break;
            default:
                break;
        }

    }

    int count = 0;
    QuietCheckPresenter.View view = new QuietCheckPresenter.View() {

        @Override
        public void onCheckSecond(long second) {
            if (btn_check!= null){
                baseActivity.runOnUiThread(() -> {
                    btn_check.setText(String.format("结束静息检测(%02d:%02d)", second / 60, second % 60));
                });
            }
        }

        @Override
        public void onSucess() {
            devicePresenter.disConnectAll();
            baseActivity.onBackPressed();
            fragmentLis.onResult(ecgDeviceInfo);
        }

        @Override
        public void onConnectSpo(boolean flag) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (flag) {
                        tv_connect_spo.setVisibility(View.GONE);
                        tv_spo.setVisibility(View.VISIBLE);
                    } else {
                        tv_connect_spo.setVisibility(View.VISIBLE);
                        tv_spo.setVisibility(View.GONE);
                    }
                    if (flag) {
                        ToastUtil.showMessage("血氧连接成功");
                    } else {
                        ToastUtil.showMessage("血氧连接失败");
                    }
                }
            });
        }

        @Override
        public void onConnectEcg(boolean flag) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    isConnectEcg = flag;
                    if (flag) {
                        tv_connect_ecg.setVisibility(View.GONE);
                        view_ecg_content.setVisibility(View.VISIBLE);
                    } else {
                        tv_connect_ecg.setVisibility(View.VISIBLE);
                        view_ecg_content.setVisibility(View.GONE);
                    }

                    if (flag) {
                        ToastUtil.showMessage("心电连接成功");
                    } else {
                        ToastUtil.showMessage("心电连接失败");
                    }
                }
            });
        }

        @Override
        public void onBpResult(BPDataBean bpDataBean) {
            tv_connect_bp.setVisibility(View.GONE);
            tv_bp.setVisibility(View.VISIBLE);
            tv_bp.setText(bpDataBean.getSystolicBp() + "/" + bpDataBean.getDiastolicBp());
        }

        @Override
        public void onHeart(int heart, int maxHeart, int minHeart) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (heart < 0) {
                        tv_heart.setText("--");
                        return;
                    }
                    tv_heart.setText(heart + "");
                    tv_heart_statistics.setText(String.format("最低：%d次/分 最高：%d次/分", minHeart,
                            maxHeart));
                }
            });
        }

        @Override
        public void onReceiveSpO2(int spo) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_spo.setText(spo + "%");
                }
            });
        }

        @Override
        public void onEcgData(byte[] bytes) {
            id_ecg_view.addEcgData(bytes);
        }
    };

    ExecteServerPresenter.View ecServerView = new ExecteServerPresenter.View() {
        @Override
        public void onEvalUserInfo(List<EvalUserInfo> evalUserInfos) {

            if (evalUserInfos.size() == 0){
                ToastUtil.showMessage("未获取到用户");
                return;
            }

            List<String> collect = new LinkedList<>();
            for (EvalUserInfo evalUserInfo : evalUserInfos) {
                collect.add(evalUserInfo.getName());
            }

            new PopDialog(baseActivity, view_user, R.layout.item_pop_eval_value, collect, "",
                    new PopDialog.SelectLis() {
                @Override
                public void onSelect(String value) {
                    for (EvalUserInfo evalUserInfo1 : evalUserInfos) {
                        if (evalUserInfo1.getName().equals(value)) {
                            evalUserInfo = evalUserInfo1;
                            tv_user.setText(evalUserInfo.getName());
                            quietCheckPresenter.setEvalUserInfo(evalUserInfo);
                            break;
                        }
                    }
                }
            });
        }

        @Override
        public void onDeviceInfo(List<DeviceInfo> deviceInfos) {
            if (deviceInfos.size() == 0){
                ToastUtil.showMessage("未获取到");
                return;
            }

            List<String> collect = new LinkedList<>();
            for (DeviceInfo evalUserInfo : deviceInfos) {
                collect.add(evalUserInfo.getEquipmentName());
            }

            new PopDialog(baseActivity, view_ecg_device, R.layout.item_pop_eval_value, collect,
                    "", new PopDialog.SelectLis() {
                @Override
                public void onSelect(String value) {
                    for (DeviceInfo deviceInfo : deviceInfos) {
                        if (deviceInfo.getEquipmentName().equals(value)) {
                            ecgDeviceInfo = deviceInfo;
                            ecgDeviceInfo.setMac("EB:F0:91:68:35:71");
                            tv_ecg.setText(deviceInfo.getEquipmentName());
                            quietCheckPresenter.setEcgDeviceInfo(ecgDeviceInfo);
                            // 绑定设备
                            execteServerPresenter.equipmentUserSchemeBind(evaluationSchemeId,
                                    ecgDeviceInfo.getId(), evalUserInfo.getUserId(),
                                    EquipmentType.ECG_EQUIPMENT);
                            try {
                                quietCheckPresenter.getSportFileManager().initEcgStore(
                                        evalUserInfo.getUserId().intValue(), evaluationSchemeId.intValue(),
                                        EvaluationStage.QUIESCENT);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            break;
                        }
                    }
                }
            });
        }
    };

}